package com.james.happyfarm.network;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Network {
	private static final Logger log = Logger.getLogger(Network.class.getName());
	
	public static final String KAIXINNETWORK = "http://www.kaixin001.com";
	public static final String KAIXINNETWORK_WAP = "http://wap.kaixin001.com";
	
	public static String callURL(String urlStr, String cookies){
		log.info("[debug] request: " + urlStr);
		StringBuffer htmlBuffer = new StringBuffer();
		try {
			URL url = new URL(urlStr);
			URLConnection connection = url.openConnection();
			connection.setRequestProperty("Cookie", cookies);
			InputStream is = connection.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
			
			String data;
			while((data = br.readLine()) != null)
				htmlBuffer.append(data);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO updateCookies();
			e.printStackTrace();
		}
		
		log.info("[debug] response: " + htmlBuffer.toString());
		return htmlBuffer.toString();
	}
	
	private static void updateCookies(){
//        KaiXinFarm.COOKIES = Network.getCookies(KaiXinFarm.USERNAME, KaiXinFarm.PASSWORD);
//        KaiXinFarm.VERIFYCODE = Network.getVerifyCode(KaiXinFarm.COOKIES);
	}

	
	public static String getCookies(String userName, String password){
		StringBuffer cookiesBuffer = new StringBuffer();
		try {
			String urlStr = KAIXINNETWORK + "/login/login.php";
			String data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(userName, "UTF-8")
				+ "&" + URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
			URL url = new URL(urlStr);
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setDoOutput(true);
			conn.setInstanceFollowRedirects(false);
			OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
			wr.write(data);
			wr.flush();
			wr.close();
			
			List<String> cookiesStrList = conn.getHeaderFields().get("Set-Cookie");
			for (String cookiesStr : cookiesStrList)
				cookiesBuffer.append(cookiesStr + ";");			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return cookiesBuffer.toString();
	}
	
	public static String getVerifyCode(String cookies){
		String respStr = callURL(KAIXINNETWORK + "/!house/garden/index.php", cookies);
		String regex = "g_verify\\s*=\\s*\"([^\"]*)\"";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(respStr);
		if(m.find())
			return m.group(1);		
		return "";
	}
	
	public static String getUID(String cookies) {
		String regex = "_uid\\s*=\\s*(\\d*);";
		Pattern p = Pattern.compile(regex);
		Matcher m = p.matcher(cookies);
		if(m.find())
			return m.group(1);
		return "";
	}
}